class_name PlayerState
extends Node

## 用来控制玩家状态和移动
@export var player: Player
@onready var state_chart: StateChart = %StateChart
@onready var idle: AtomicState = %idle
@onready var run: AtomicState = %run
@onready var die: AtomicState = %die
@onready var hurt: AtomicState = %hurt
@onready var player_animations: PlayerAnimations = %PlayerAnimations
@onready var animation_player: AnimationPlayer = %AnimationPlayer

func _ready() -> void:
	idle.state_physics_processing.connect(on_idle_physics_processing)
	run.state_physics_processing.connect(on_run_physics_processing)
	die.state_entered.connect(on_die_entered)
	hurt.state_entered.connect(on_hurt_entered)
	hurt.state_physics_processing.connect(on_hurt_physics_processing)
	
func state_send_event(_name: String):
	state_chart.send_event(_name)

func changeAnim(move_direction):
	if move_direction != Vector2.ZERO:
		state_send_event("idle_to_run")
	else:
		state_send_event("run_to_idle")

## 闲置状态
func on_idle_physics_processing(_delte):
	animation_player.play("idle")

## 跑步状态
func on_run_physics_processing(_delte):
	player.velocity = player.direction * (player.player_stats.get_integer("move_speed") + player.player_stats.get_integer("additional_move_speed"))
	changeAnim(player.direction)
	animation_player.play("run")
	player.move_and_slide()

## 死亡状态进入
func on_die_entered():
	animation_player.play("die")
	player.buff_manager.clear_all()
	Utils.set_player_stats_value("health_regen", -Utils.get_player_stats_value("health_regen"))
	Utils.set_player_stats_value("mp_regen", -Utils.get_player_stats_value("mp_regen"))
	
## 受伤状态进入
func on_hurt_entered():
	animation_player.play("hurt")
	await animation_player.animation_finished
	state_send_event("hurt_to_idle")

## 受伤也能跑
func on_hurt_physics_processing(_delte):
	player.velocity = player.direction * player.player_stats.get_integer("move_speed")
	changeAnim(player.direction)
	player.move_and_slide()


func _on_hurt_box_component_on_hurt() -> void:
	state_send_event("to_hurt")
